package com.xunfang.demo.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import java.io.IOException;

//过滤器处理编码问题
@WebFilter(filterName = "CodeFilter",urlPatterns = "/*",
        initParams = {@WebInitParam(name="encoding",value = "utf-8")})
public class CodeFilter implements Filter {
    String code = "";
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        code = filterConfig.getInitParameter("encoding");
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        req.setCharacterEncoding(code);
        resp.setContentType("text/html;charset="+code);
        //放行的方法
        chain.doFilter(req, resp);
    }
}
